package com.uam.utils.file.analysis.help;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.uam.common.exception.UamException;
import lombok.extern.slf4j.Slf4j;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.geojson.feature.FeatureJSON;
import org.opengis.feature.simple.SimpleFeature;

import java.io.File;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author heguanglong
 * shp转 geojson 做数据校验
 */
@Slf4j
public class Shp2GeoJson extends AnalysisParent implements File2GeoJson {
    @Override
    public RetAnalysisVo fileToGeoJsonFile(String fileUrl, String targetUrl, String fileName) {
        FeatureJSON fjson = new FeatureJSON();
        try {
            StringBuffer sb = new StringBuffer();
            sb.append("{    \"type\": \"FeatureCollection\",    \"features\": ");
            File file = new File(fileUrl);
            ShapefileDataStore shpDataStore = null;
            shpDataStore = new ShapefileDataStore(file.toURL());
            //设置编码
            Charset charset = Charset.forName("GBK");
            shpDataStore.setCharset(charset);
            String typeName = shpDataStore.getTypeNames()[0];
            SimpleFeatureSource featureSource = null;
            featureSource = shpDataStore.getFeatureSource(typeName);
            SimpleFeatureCollection result = featureSource.getFeatures();
            SimpleFeatureIterator itertor = result.features();
            JSONArray array = new JSONArray();
            while (itertor.hasNext()) {
                SimpleFeature feature = itertor.next();
                StringWriter writer = new StringWriter();
                fjson.writeFeature(feature, writer);
                JSONObject json = JSONObject.parseObject(writer.toString());
                array.add(json);
            }
            itertor.close();
            sb.append(array.toString());
            sb.append("}");
            return toGeoJsonFile(sb.toString(), targetUrl, fileName);
        } catch (Exception e) {
            log.error("shp 文件解析报错：{}", e.getMessage());
            throw UamException.fileTypeError("shp 文件解析报错");
        }
    }


}
